package com.cxdr.awsips.distribute;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.cxdr.awsips.common.logger.LogFactory;
import com.cxdr.awsips.distribute.config.LinkConfig;
import com.cxdr.awsips.distribute.config.SystemConfig;
import com.cxdr.awsips.distribute.processor.DistributeWorker;
import com.cxdr.awsips.distribute.processor.StoreDistributeProccessor;
import com.cxdr.awsips.distribute.processor.StoreReportProccessor;

public class Server {
	private static Logger logger = LogFactory.makeNewLogger(Server.class);
	private static Map<String,DistributeWorker> workers = new HashMap<String,DistributeWorker>();
	private static StoreReportProccessor reportProccessor = null; //new StoreReportProccessor();
	private static StoreDistributeProccessor storeDistributeProccessor = null;//new StoreDistributeProccessor();
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		logger.info("*********************************");
		logger.info("开始分发系统服务器");
		logger.info("*********************************");
		Server start = new Server();
		init();
		start.start();
	}
	
	public DistributeWorker regWorker(DistributeWorker worker){
		 return workers.put(worker.getKey(), worker) ;
	}
	public DistributeWorker unregWorker(DistributeWorker worker){
		worker.stopWork();
		return workers.remove(worker.getKey());
	}
	public DistributeWorker startNewWork(LinkConfig link){
		DistributeWorker worker = DistributeWorker.getWorker(link);
		worker.startWork();
		return regWorker(worker);
	}
	public void stopWork(String key){
		DistributeWorker worker = workers.get(key);
		if(worker !=null){
			worker.stopWork();
		}
	}
	public static void init() throws Exception{
		SystemConfig.load();
		LinkConfig.init();
		reportProccessor = new StoreReportProccessor();
		storeDistributeProccessor = new StoreDistributeProccessor();
	}
	public void start() {
		
		//开启到报信息处理器
		reportProccessor.start();
		//开启分发日志入库信息处理器
		storeDistributeProccessor.start();
		for(LinkConfig link:LinkConfig.getAllLink()){
			DistributeWorker worker = DistributeWorker.getWorker(link);
			worker.startWork();
			regWorker(worker);
		}
	}
}
